import getUserTempId from "@/utils/userTempId";
import { SET_USERTOKEN_STATE, SET_USERINFO_STATE, RESET_USER_STATE } from "../constant-type";
import { reqLogin, reqUserInfo, reqLogout } from "@/api";
import { getToken, setToken, removeToken } from "@/utils/token";
const state = {
    userTempId: getUserTempId(),
    token: getToken() || "",
    userInfo: {},
};
const mutations = {
    //1. 修改vuex数据token的值
    [SET_USERTOKEN_STATE](state, payload) {
        state.token = payload.token;
        //持久化存储token
        setToken(payload.token);
    },
    //2.修改vuex数据userInfo的值
    [SET_USERINFO_STATE](state, payload) {
        state.userInfo = payload.userInfo;
    },
    //3.重置token和user数据
    [RESET_USER_STATE](state) {
        state.token = ""; //清除token
        removeToken(); //清除持久化存储的token
        state.userInfo = {}; //清除用户信息
    },
};
const actions = {
    //1.登录请求获取token
    async reqLogin({ commit }, userInfo) {
        try {
            const result = await reqLogin(userInfo);
            // console.log(result);
            commit(SET_USERTOKEN_STATE, result);
        } catch (e) {
            alert(e.message);
            return Promise.reject();//这样就算是异常了,可以让调用函数的地方得到一个失败的Promise进行异常处理
        }
    },
    //2.请求用户信息
    async getUserInfo({ commit }) {
        try {
            const result = await reqUserInfo();
            // console.log(result, "result");
            commit(SET_USERINFO_STATE, { userInfo: result });
        } catch (e) {
            alert(e.message);
            return Promise.reject(e)//因为当前函数已经使用try处理异常了,所以在调用函数的地方无法得到异常存在,所以需要我们在catch的位置进行抛出失败的promise,则当前函在失败的情况下就会返回失败的promise
        }
    },
    //3.退出登录
    async getLogout({ commit }) {
        try {
            await reqLogout();
            alert("退出登录成功");
            //清理数据
            commit(RESET_USER_STATE);
        } catch (e) {
            alert(e.message);
        }
    },

    //4. 清理user数据的action方法
    resetToken({ commit }) {
        commit(RESET_USER_STATE);
    },
};



export default {
    namespaced: true,
    state,
    mutations,
    actions,
};